<template>
    <div>
        <el-dialog title="新增烟感配置" :visible.sync="dialogVisible" width="500px" :before-close="closeEditDialog"
            :close-on-click-modal="false" :append-to-body="true">
            <el-form :model="addInfo" :rules="rules" ref="refAddInfo" label-width="110px">

                <el-form-item size="small" label="目标类型" prop="targetType">
                    <el-select v-model="addInfo.targetType" filterable placeholder="请选择" style="width: 350px;"
                        class="elSelect" @change="targetTypeChange">
                        <el-option v-for="(item, i) in targetTypeList" :key="i" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="租户名称" prop="tenantId" v-if="tenantFlag">
                    <el-select v-model="addInfo.tenantId" filterable placeholder="请选择" size="small"
                        style="width: 350px;" class="elSelect" @visible-change="tenantIdChange" @change="tenantChange"
                        v-loadMore="loadMore">
                        <el-option v-for="(item, i) in enterpriseList" :key="i" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"> </div>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="组织机构" prop="orgId" v-if="orgFlag">
                    <!-- <el-select v-model="addInfo.orgId" filterable placeholder="请选择组织机构" style="width: 350px;"
                        class="elSelect" @change="orgIdChange" v-loadMore="loadMoreorg">
                        <el-option v-for="(item, i) in orgList" :key="i" :label="item.orgName" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loadingorg" :style="loadingorg ? '' : 'display: none;'"> </div>
                    </el-select> -->

                    <TreeSearchAdd style="width: 100%" @changeOrgId="changeOrgId" @onClear="onClear" :addtenantId="addInfo.tenantId"
                        ref="refTreeSearchAdd">
                    </TreeSearchAdd>

                </el-form-item>

                <el-form-item size="small" label="所属建筑物" prop="parentId" v-if="parentFlag">
                    <el-select v-model="addInfo.parentId" filterable placeholder="请选择" style="width: 350px"
                        class="elSelect" @change="parentIdChange" v-loadMore="loadMoreparent">
                        <el-option v-for="item in buildings" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loadingParent" :style="loadingParent ? '' : 'display: none;'">
                        </div>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="所属楼层" prop="floorId" v-if="floorFlag">
                    <el-select v-model="addInfo.floorId" filterable placeholder="请选择" style="width: 350px"
                        v-loadMore="loadMorefloor" @change="floorIdChange">
                        <el-option v-for="item in floor" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loadingfloor" :style="loadingfloor ? '' : 'display: none;'">
                        </div>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="安装点" prop="spaceId" v-if="spaceFlag">
                    <el-select filterable v-model="addInfo.spaceId" placeholder="请选择" style="width: 100%"
                        v-loadMore="loadMorespace">
                        <el-option v-for="item in spaceList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loadingspace" :style="loadingspace ? '' : 'display: none;'">
                        </div>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="设备编码" prop="deviceId" v-if="deviceFlag">
                    <el-select v-model="addInfo.deviceId" filterable placeholder="请选择" size="small"
                        style="width: 350px;" class="elSelect" clearable @visible-change="deviceChange"
                        v-loadMore="loadMoredevice" remote :remote-method="remoteMethod">
                        <el-option v-for="(item, i) in deviceList" :key="i" :label="item.imei" :value="item.id">
                        </el-option>
                        <div class="div_box" v-loading="loadingDevice" :style="loadingDevice ? '' : 'display: none;'">
                        </div>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="阈值策略时间" prop="time">
                    <el-input clearable v-model.trim="addInfo.time" placeholder="请输入（分钟）" maxlength="2" oninput="{ value=value.replace(/\D/g,'') }  
           {if(value=='0')value=1}  {if(value>60)value=60}"></el-input>
                </el-form-item>

                <el-form-item size="small" label="阈值策略次数" prop="number">
                    <el-input clearable v-model.trim="addInfo.number" placeholder="请输入" maxlength="2" oninput="{ value=value.replace(/\D/g,'') }  
           {if(value=='0')value=1}  {if(value>10)value=10}"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
                <el-button size="small" @click="editSubmit" v-preventReClick="1000" class="confirm-button">确
                    定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { handleTree } from "@utils/trans-tree";
import {
    reqSpaceManager,
    reqOrgList,
    reqSmokeAlarmConfigAdd,
    reqTenantList,
    reqTerminalList
} from "@/api/api";
import { mapState } from "vuex";
import treeselect from "@riophae/vue-treeselect"; //树形选择器
import "@components/vue-treeselect.less"; //树形选择器
import { LOAD_CHILDREN_OPTIONS } from "@riophae/vue-treeselect"; //Vue-Treeselect三级动态加载
import loadMore from "@mixin/loadMore";
import TreeSearchAdd from "@components/TreeSearchAdd.vue";

export default {
    name: "add",
    components: { treeselect, TreeSearchAdd },
    mixins: [loadMore],
    data() {
        return {
            normalizer(node) {
                return {
                    id: node.id,
                    label: node.orgName,
                    children: node.children,
                };
            },
            targetTypeList: [
                {
                    id: 1,
                    name: '租户'
                }, {
                    id: 2,
                    name: '组织机构'
                },
                // {
                //     id: 3,
                //     name: '建筑物'
                // }, {
                //     id: 4,
                //     name: '楼层'
                // }, {
                //     id: 5,
                //     name: '安装点'
                // },
                {
                    id: 6,
                    name: '设备'
                },
            ],

            dialogVisible: false,
            addInfo: {
                targetType: "",
                targetId: "",
                time: '',
                number: '',

                tenantId: '',
                orgId: '',
                parentId: '',
                floorId: '',
                spaceId: '',
                deviceId: ''
            },
            // 表单验证规则
            rules: {
                time: [
                    {
                        required: true,
                        message: "请输入阈值策略时间",
                        trigger: "blur",
                    },
                ],
                number: [
                    {
                        required: true,
                        message: "请输入阈值策略次数",
                        trigger: "blur",
                    },
                ],
                targetType: [
                    {
                        required: true,
                        message: "请选择目标类型",
                        trigger: ["blur", "change"],
                    },
                ],
                tenantId: [
                    {
                        required: true,
                        message: "请选择租户名称",
                        trigger: ["blur", "change"],
                    },
                ],
                orgId: [
                    {
                        required: true,
                        message: "请选择组织机构",
                        trigger: ["change"],
                    },
                ],
                floorId: [
                    {
                        required: true,
                        message: "请选择所属楼层",
                        trigger: "change",
                    },
                ],
                parentId: [
                    {
                        required: true,
                        message: "请选择所属建筑物",
                        trigger: "change",
                    },
                ],
                spaceId: [
                    {
                        required: true,
                        message: "请选择安装点",
                        trigger: "change",
                    },
                ],
                deviceId: [
                    {
                        required: true,
                        message: "请选择设备编码",
                        trigger: "change",
                    },
                ],
            },

            // 租户
            enterpriseList: [],
            sysInstanceIndex: 1,
            sysInstanceTotalPages: 10,
            loading: false,
            tenantIdflag: true,
            tenantFlag: false,

            // 组织机构
            orgList: [],
            sysInstanceIndexorg: 1,
            sysInstanceTotalPagesorg: 10,
            loadingorg: false,
            orgFlag: false,

            // 建筑物
            buildings: [],
            sysInstanceIndexParent: 1,
            sysInstanceTotalPagesParent: 10,
            loadingParent: false,
            parentFlag: false,

            // 楼层
            floor: [],
            sysInstanceIndexfloor: 1,
            sysInstanceTotalPagesfloor: 10,
            loadingfloor: false,
            floorFlag: false,

            // 安装点
            spaceList: [],
            sysInstanceIndexspace: 1,
            sysInstanceTotalPagesspace: 10,
            loadingspace: false,
            spaceFlag: false,

            // 设备
            deviceList: [],
            sysInstanceIndexdevice: 1,
            sysInstanceTotalPagesdevice: 10,
            loadingDevice: false,
            deviceFlag: false,
            deviceIdflag: true,
        };
    },
    watch: {},
    computed: {
        ...mapState(["user"]),
    },
    methods: {
        changeOrgId(instanceId) {
            this.addInfo.orgId = instanceId.id;
            this.buildings = []
            this.sysInstanceIndexParent = 1
            this.sysInstanceTotalPagesParent = 10
            this.addInfo.parentId = ''

            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10
            this.addInfo.floorId = ''

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.addInfo.spaceId = ''
            this.SpaceManager2()
        },
        onClear() {
            this.addInfo.orgId =
                this.buildings = []
            this.sysInstanceIndexParent = 1
            this.sysInstanceTotalPagesParent = 10
            this.addInfo.parentId = ''

            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10
            this.addInfo.floorId = ''

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.addInfo.spaceId = ''
        },
        async remoteMethod(query) {
            if (query != '') {
                var res = await reqTerminalList(this.sysInstanceIndexdevice, 10, {
                    productId: '1612276823406194689',
                    imei: query
                });
                // console.log(res);
                if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                this.deviceList = res.data.rows || []
            } else {
                this.deviceList = []
            }
        },
        targetTypeChange(e) {
            this.addInfo.tenantId=''
            // console.log(e);
            this.tenantFlag = false;
            this.orgFlag = false;
            this.parentFlag = false;
            this.floorFlag = false;
            this.spaceFlag = false;
            this.deviceFlag = false;
            if (e == 1) {
                this.tenantFlag = true;
            } else if (e == 2) {
                this.tenantFlag = true;
                this.orgFlag = true;
            } else if (e == 3) {
                this.tenantFlag = true;
                this.orgFlag = true;
                this.parentFlag = true
            } else if (e == 4) {
                this.tenantFlag = true;
                this.orgFlag = true;
                this.parentFlag = true
                this.floorFlag = true;
            } else if (e == 5) {
                this.tenantFlag = true;
                this.orgFlag = true;
                this.parentFlag = true
                this.floorFlag = true;
                this.spaceFlag = true;
            } else if (e == 6) {
                this.deviceFlag = true;
            }
        },

        // 下拉请求列表
        tenantIdChange(val) {
            if (val && this.tenantIdflag) {
                this.getEnterpriseList();
                this.tenantIdflag = false;//只执行一次
            }
        },
        // 获取租户列表
        async getEnterpriseList() {
            var res = await reqTenantList(this.sysInstanceIndex, 10);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPages = res.data.total
            this.enterpriseList = [...this.enterpriseList, ...res.data.rows]
        },
        async loadMore() {
            if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10)) return
            this.sysInstanceIndex++
            this.loading = true;
            // 获取列表数据的方法
            await this.getEnterpriseList()
            this.loading = false;
        },
        // 租户切换
        tenantChange() {
            this.orgList = []
            this.sysInstanceIndexorg = 1
            this.sysInstanceTotalPagesorg = 10
            this.addInfo.orgId = ''

            this.buildings = []
            this.sysInstanceIndexParent = 1
            this.sysInstanceTotalPagesParent = 10
            this.addInfo.parentId = ''

            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10
            this.addInfo.floorId = ''

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.addInfo.spaceId = ''

            // this.getOrgList()
            this.$nextTick(()=>{
                this.$refs.refTreeSearchAdd.onclose()
                this.$refs.refTreeSearchAdd.getDataList()
            })
        },


        // 请求组织机构
        async getOrgList() {
            const res = await reqOrgList( {
                tenantId: this.addInfo.tenantId,
                userId: this.user.userId,
                roleName: 'TENANT_ADMIN',
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.orgList =res.data.rows
        },
        async loadMoreorg() {
            if (this.sysInstanceIndexorg >= Math.ceil(this.sysInstanceTotalPagesorg / 10)) return
            this.sysInstanceIndexorg++
            this.loadingorg = true;
            // 获取列表数据的方法
            await this.getOrgList()
            this.loadingorg = false;
        },
        orgIdChange() {
            this.buildings = []
            this.sysInstanceIndexParent = 1
            this.sysInstanceTotalPagesParent = 10
            this.addInfo.parentId = ''

            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10
            this.addInfo.floorId = ''

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.addInfo.spaceId = ''
            this.SpaceManager2()
        },


        // 建筑物列表
        async SpaceManager2() {
            let res = await reqSpaceManager(this.sysInstanceIndexParent, 10, {
                userId: this.user.userId,
                roleName: 'TENANT_ADMIN',
                metaCode: 1,
                orgId: this.addInfo.orgId,
                isStatistics: 0
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPagesParent = res.data.total
            this.buildings = [...this.buildings, ...res.data.rows]
        },
        async loadMoreparent() {
            if (this.sysInstanceIndexParent >= Math.ceil(this.sysInstanceTotalPagesParent / 10)) return
            this.sysInstanceIndexParent++
            this.loadingParent = true;
            // 获取列表数据的方法
            await this.SpaceManager2()
            this.loadingParent = false;
        },
        parentIdChange() {
            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10
            this.addInfo.floorId = ''

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.addInfo.spaceId = ''
            this.SpaceManager()
        },

        // 楼层列表
        async SpaceManager() {
            let res = await reqSpaceManager(this.sysInstanceIndexfloor, 10, {
                userId: this.user.userId,
                roleName: 'TENANT_ADMIN',
                metaCode: 2,
                orgId: this.addInfo.orgId,
                parentId: this.addInfo.parentId,//建筑物id
                isStatistics: 0
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPagesfloor = res.data.total
            this.floor = [...this.floor, ...res.data.rows]
        },
        async loadMorefloor() {
            if (this.sysInstanceIndexfloor >= Math.ceil(this.sysInstanceTotalPagesfloor / 10)) return
            this.sysInstanceIndexfloor++
            this.loadingfloor = true;
            // 获取列表数据的方法
            await this.SpaceManager()
            this.loadingfloor = false;
        },
        floorIdChange() {
            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10
            this.getSpaceList()
        },

        // 获取安装点列表
        async getSpaceList() {
            let res = await reqSpaceManager(this.sysInstanceIndexspace, 10, {
                userId: this.user.userId,
                roleName: 'TENANT_ADMIN',
                orgId: this.addInfo.orgId,
                parentId: this.addInfo.floorId,
                metaCode: 3,
                isStatistics: 0
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPagesspace = res.data.total
            this.spaceList = [...this.spaceList, ...res.data.rows]
        },
        async loadMorespace() {
            if (this.sysInstanceIndexspace >= Math.ceil(this.sysInstanceTotalPagesspace / 10)) return
            this.sysInstanceIndexspace++
            this.loadingspace = true;
            // 获取列表数据的方法
            await this.getSpaceList()
            this.loadingspace = false;
        },


        // 设备
        deviceChange(val) {
            // if (val && this.deviceIdflag) {
            //     this.getDeviceList();
            //     this.deviceIdflag = false;//只执行一次
            // }
        },
        // 获取设备列表
        async getDeviceList() {
            var res = await reqTerminalList(this.sysInstanceIndexdevice, 10, {
                productId: '1612276823406194689'
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.sysInstanceTotalPagesdevice = res.data.total
            this.deviceList = [...this.deviceList, ...res.data.rows]
        },
        async loadMoredevice() {
            if (this.sysInstanceIndexdevice >= Math.ceil(this.sysInstanceTotalPagesdevice / 10)) return
            this.sysInstanceIndexdevice++
            this.loadingDevice = true;
            // 获取列表数据的方法
            await this.getDeviceList()
            this.loadingDevice = false;
        },

        // 点击
        async editSubmit() {
            this.$refs.refAddInfo.validate(async (valid) => {
                if (valid) {

                    if (this.addInfo.targetType == 1) {
                        this.addInfo.targetId = this.addInfo.tenantId
                    } else if (this.addInfo.targetType == 2) {
                        this.addInfo.targetId = this.addInfo.orgId
                    } else if (this.addInfo.targetType == 3) {
                        this.addInfo.targetId = this.addInfo.parentId
                    } else if (this.addInfo.targetType == 4) {
                        this.addInfo.targetId = this.addInfo.floorId
                    } else if (this.addInfo.targetType == 5) {
                        this.addInfo.targetId = this.addInfo.spaceId
                    } else if (this.addInfo.targetType == 6) {
                        this.addInfo.targetId = this.addInfo.deviceId
                    }
                    const res = await reqSmokeAlarmConfigAdd({
                        time: this.addInfo.time,
                        number: this.addInfo.number,
                        targetType: this.addInfo.targetType,
                        targetId: this.addInfo.targetId,
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

                    this.$modal.notifySuccess("新增烟感配置成功");
                    this.closeEditDialog();
                    this.$parent.getDataList(); //更新
                }
            });
        },
        // 点击关闭弹框
        closeEditDialog() {
            this.orgList = []
            this.sysInstanceIndexorg = 1
            this.sysInstanceTotalPagesorg = 10

            this.buildings = []
            this.sysInstanceIndexParent = 1
            this.sysInstanceTotalPagesParent = 10

            this.floor = []
            this.sysInstanceIndexfloor = 1
            this.sysInstanceTotalPagesfloor = 10

            this.spaceList = []
            this.sysInstanceIndexspace = 1
            this.sysInstanceTotalPagesspace = 10

            this.deviceList = []
            this.sysInstanceIndexdevice = 1
            this.sysInstanceTotalPagesdevice = 10

            this.enterpriseList = []
            this.sysInstanceIndex = 1
            this.sysInstanceTotalPages = 10

            this.tenantFlag = false;
            this.orgFlag = false;
            this.parentFlag = false;
            this.floorFlag = false;
            this.spaceFlag = false;
            this.tenantIdflag = true;
            this.deviceFlag = false;
            this.deviceIdflag = true;

            this.addInfo = {
                targetType: "",
                targetId: "",
                time: '',
                number: '',

                tenantId: '',
                orgId: '',
                parentId: '',
                floorId: '',
                spaceId: '',
                deviceId: ''
            };
            this.$refs.refAddInfo.resetFields();
            this.dialogVisible = false;
        },
    },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

// 下拉框加载开始
.div_box {
    height: 276px;
    position: absolute;
    top: -1px;
    left: -1px;
    width: 100%;
    z-index: 2016;
    // background: red;
    // opacity: 0.5;
}

::v-deep .el-loading-mask {
    border-radius: 4px;
}

// 下拉框加载结束
::v-deep .el-radio {
    color: @primaryThemeTxtColor2;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
    color: #7367F0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
    border-color: #7367F0;
    background: #7367F0;
}

.zuobiao2 {
    color: @primaryTxtcolor;
}
</style>